package utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CodeUtil {
    private static int codeLength = 5;
    private static int singlecodeWidth = 15;
    private static int singlecodeHeight = 30;
    private static int singlecodeGap = 5;
    private static int imgWidth = codeLength * (singlecodeWidth + singlecodeGap);
    private static int imgHeight = singlecodeHeight;

    public static String getCode() {
        String code = "";
        for (int i = 0; i < codeLength; i++) {
            code += (new Random()).nextInt(10);
        }
        return code;
    }

    public static BufferedImage getCodeImg(String code) {
        BufferedImage img = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(Color.yellow);
        g.fillRect(0, 0, imgWidth, imgHeight);
        g.setColor(Color.black);
        g.setFont(new Font("宋体", Font.PLAIN, singlecodeHeight+5));

        char c;
        for(int i=0;i<code.toCharArray().length;i++) {
            c=code.charAt(i);
            g.drawString(c+"", i*(singlecodeWidth+singlecodeGap)+singlecodeGap/2, imgHeight);
        }
        Random random = new Random();
        //绘制干扰线
        for(int i=0;i<10;i++) {
            int x = random.nextInt(imgWidth);
            int y = random.nextInt(imgHeight);
            int x2 = random.nextInt(imgWidth);
            int y2 = random.nextInt(imgHeight);
            g.drawLine(x, y, x+x2, y+y2);
        }
        return img;
    }
}
